import router, { notFoundRoute, constantRoutes } from "@/router";
import { selectAllUserMenus } from "@/api/menu";
import { defineStore } from "pinia";
import { ref } from "vue";
import type { RouteRecordRaw } from "vue-router";

// 匹配views里面所有的.vue文件
const modules = import.meta.glob([
  "/src/views/**/*.vue",
  "/src/components/**/*.vue",
]);

// 菜单项接口定义
interface MenuItem {
  menuId: number;
  parentId: number;
  name: string;
  path: string;
  redirect?: string;
  component: string;
  query?: string;
  alwaysShow?: boolean;
  meta: {
    title: string;
    icon?: string;
    noCache: boolean;
    link?: string;
  };
  children: MenuItem[];
}

export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([]);
  const addRoutes = ref<RouteRecordRaw[]>([]);
  const routesGenerated = ref(false); // 路由是否已生成标志
  const notFoundRouteAdded = ref(false); // 404路由是否已添加标志

  // 转换组件路径为动态导入函数
  const loadView = (view: string) => {
    // 统一路径格式
    if (view.startsWith("@/")) {
      view = view.replace("@", "/src");
    } else if (!view.startsWith("/src")) {
      view = `/src${view.startsWith("/") ? "" : "/"}${view}`;
    }

    const matchedModule = modules[view];

    if (!matchedModule) {
      console.error(`找不到组件: ${view}`);
      return () => import("@/views/NotFound.vue");
    }

    return matchedModule;
  };

  // 将菜单数据转换为路由配置
  const filterAsyncRoutes = (
    menuList: MenuItem[],
    parentName = ""
  ): RouteRecordRaw[] => {
    const res: RouteRecordRaw[] = [];

    menuList.forEach((menu) => {
      const routeName = parentName
        ? `${parentName}-${menu.menuId}`
        : `Menu-${menu.menuId}`;

      // 确保路径是相对路径（去掉开头的/）
      const routePath = menu.path.startsWith("/")
        ? menu.path.substring(1)
        : menu.path;

      const route: RouteRecordRaw = {
        name: routeName,
        path: routePath,
        component: loadView(menu.component),
        meta: {
          title: menu.meta.title,
          icon: menu.meta.icon,
          noCache: menu.meta.noCache,
          link: menu.meta.link,
          menuId: menu.menuId,
          showInSidebar: true,
          isTopLevel: parentName === "", // 顶级菜单标记
        },
      };

      if (menu.redirect) {
        route.redirect = menu.redirect;
      }

      if (menu.children && menu.children.length > 0) {
        route.children = filterAsyncRoutes(menu.children, routeName);
      }

      res.push(route);
    });

    return res;
  };

  const generateRoutes = async (): Promise<RouteRecordRaw[]> => {
    // 如果已经生成过路由，直接返回
    if (routesGenerated.value) {
      return addRoutes.value;
    }

    return new Promise((resolve, reject) => {
      selectAllUserMenus()
        .then((res) => {
          const menuData: MenuItem[] = res.data;
          console.log("获取到的菜单数据:", menuData);

          // 转换菜单数据为路由配置
          const asyncRoutes = filterAsyncRoutes(menuData);
          console.log("转换后的路由配置:", asyncRoutes);

          // 存储菜单数据到sessionStorage，解决刷新问题
          sessionStorage.setItem("menuData", JSON.stringify(menuData));

          // 先移除之前添加的动态路由（避免重复）
          addRoutes.value.forEach((route) => {
            if (route.name && router.hasRoute(route.name)) {
              router.removeRoute(route.name);
            }
          });

          // 添加新的动态路由作为MainLayout的子路由
          asyncRoutes.forEach((route) => {
            if (route.name && !router.hasRoute(route.name)) {
              router.addRoute("Root", route); // 添加到Root路由下
            }
          });

          // 确保404路由最后添加
          if (!notFoundRouteAdded.value) {
            router.addRoute(notFoundRoute);
            notFoundRouteAdded.value = true;
          }

          addRoutes.value = asyncRoutes;
          routes.value = [...router.getRoutes()];
          routesGenerated.value = true;

          resolve(asyncRoutes);
        })
        .catch((error) => {
          console.error("获取菜单数据失败:", error);
          reject(error);
        });
    });
  };

  // 从sessionStorage恢复路由
  const restoreRoutesFromStorage = () => {
    if (routesGenerated.value) return true;

    const menuDataStr = sessionStorage.getItem("menuData");
    if (menuDataStr) {
      try {
        const menuData: MenuItem[] = JSON.parse(menuDataStr);
        const asyncRoutes = filterAsyncRoutes(menuData);

        // 添加动态路由
        asyncRoutes.forEach((route) => {
          if (route.name && !router.hasRoute(route.name)) {
            router.addRoute("Root", route);
          }
        });

        // 确保404路由最后添加
        if (!notFoundRouteAdded.value) {
          router.addRoute(notFoundRoute);
          notFoundRouteAdded.value = true;
        }

        addRoutes.value = asyncRoutes;
        routes.value = [...router.getRoutes()];
        routesGenerated.value = true;
        return true;
      } catch (e) {
        console.error("从存储恢复路由失败:", e);
        sessionStorage.removeItem("menuData");
      }
    }
    return false;
  };

  // 清除路由
  const clearRoutes = () => {
    addRoutes.value.forEach((route) => {
      if (route.name && router.hasRoute(route.name)) {
        router.removeRoute(route.name);
      }
    });

    // 移除404路由
    if (notFoundRouteAdded.value) {
      router.removeRoute(notFoundRoute.name!);
      notFoundRouteAdded.value = false;
    }

    addRoutes.value = [];
    routes.value = constantRoutes;
    routesGenerated.value = false;
    sessionStorage.removeItem("menuData");
  };

  return {
    routes,
    addRoutes,
    routesGenerated,
    generateRoutes,
    restoreRoutesFromStorage,
    clearRoutes,
  };
});
